﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// <summary>
/// DESEncrypt加密解密算法。
/// </summary>
public class DESEncrypt
{
    DESCryptoServiceProvider des;
    ICryptoTransform encrpty;
    ICryptoTransform decrypt;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="key">8字节</param>
    /// <param name="iv">8字节</param>
    public DESEncrypt(string key, string iv)
    {
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        des.Key = ASCIIEncoding.ASCII.GetBytes(key);// 密匙
        des.IV = ASCIIEncoding.ASCII.GetBytes(iv);// 初始化向量
        encrpty = des.CreateEncryptor();
        decrypt = des.CreateDecryptor();
    }
    /// <summary>
    /// DES加密
    /// </summary>
    /// <param name="inputByteArray"></param>
    /// <param name="ms"></param>
    public void Encrypt(byte[] inputByteArray, Stream ms)
    {
        CryptoStream cs = new CryptoStream(ms, encrpty, CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
    }
    /// <summary>
    /// DES加密
    /// </summary>
    /// <param name="inputByteArray"></param>
    /// <param name="ms"></param>
    public void EncryptMS(byte[] inputByteArray, MemoryStream ms)
    {
        ms.SetLength(0);
        ms.Seek(0, SeekOrigin.Begin);
        Encrypt(inputByteArray, ms);
    }
    /// <summary>
    /// DES解密
    /// </summary>
    /// <param name="inputByteArray"></param>
    /// <param name="ms"></param>
    public void Decrypt(byte[] inputByteArray,Stream ms)
    {
        CryptoStream cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        // 如果两次密匙不一样，这一步可能会引发异常
        cs.FlushFinalBlock();
    }
    /// <summary>
    /// DES解密
    /// </summary>
    /// <param name="inputByteArray"></param>
    /// <param name="ms"></param>
    public void DecryptMS(byte[] inputByteArray, MemoryStream ms)
    {
        ms.SetLength(0);
        ms.Seek(0, SeekOrigin.Begin);
        Decrypt(inputByteArray,ms);
    }
    public void Dipsose()
    {
        if(des!=null)
        {
            des.Dispose();
            encrpty.Dispose();
            decrypt.Dispose();
            des = null;
            encrpty = null;
            decrypt = null;
        }
    }
}
